//病虫害插值分析
var map;
var stationIdNames;
var stationIdValues;
var levelColors;
var stationIdColors;
var renderPanel;
var geometryService = null;
var resultImageLayer = null;
var isSetMask = false;
var resultRecoders = {};
var hasWarning = {};
var weightFieldName="";
var UserInputPre="";
//界面布局
require(["dojo/parser", "dijit/layout/ContentPane", "dijit/layout/BorderContainer"]);

//地图导航工具
require([
        "esri/geometry/Point",
        "esri/map",
        "esri/layers/ArcGISDynamicMapServiceLayer",
        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/GraphicsLayer",
        "esri/graphic",
        "esri/symbols/PictureMarkerSymbol",
        "esri/toolbars/navigation",
        "dijit/form/Button",
        "esri/config",
        "dojo/on",
        "dojo/dom",
        "dojo/domReady!"
    ],
    function (Point, Map, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, GraphicsLayer, Graphic, PictureMarkerSymbol, Navigation, Button, esriConfig, on, dom) {

        $('#operationMask').hide();
        $('.legend').hide();

        esriConfig.defaults.io.proxyUrl = 'DotNet/proxy.ashx';
        esriConfig.defaults.io.alwaysUseProxy = true;

        map = new Map("mapDiv", {
            logo: false,
            scale: 50000
        });
        var basemap = new ArcGISTiledMapServiceLayer(basemapServerUrl);
        basemap.setOpacity(0.7);
        map.addLayer(basemap);
        map.centerAndZoom(new Point(115.6, 25.5, {
            "wkid": wkidValue
        }), 7);

        //创建地图操作对象
        var navToolbar = new Navigation(map);
        //创建按钮并绑定事件
        var zoomInBtn = new Button({
            onClick: function () {
                navToolbar.activate(Navigation.ZOOM_IN);
            }
        }, "zoomIn").startup(); //放大
        var zoomOutBtn = new Button({
            onClick: function () {
                navToolbar.activate(Navigation.ZOOM_OUT);
            }
        }, "zoomOut").startup(); //缩小
        var panBtn = new Button({
            onClick: function () {
                navToolbar.activate(Navigation.PAN);
            }
        }, "pan").startup(); //平移
        var zoomFullBtn = new Button({
            onClick: function () {
                map.centerAndZoom(new Point(113.1, 23.5, {
                    "wkid": wkidValue
                }), 7);
            }
        }, "zoomFull").startup(); //全图
        var preExtentBtn = new Button({
            onClick: function () {
                navToolbar.zoomToPrevExtent();
            }
        }, "preExtent").startup(); //前一视图
        var nextExtentBtn = new Button({
            onClick: function () {
                navToolbar.zoomToNextExtent();
            }
        }, "nextExtent").startup(); //后一视图

        // on(dom.byId('idwBtn'), 'click', IdwInterpolateAnalyse_Click);
        // on(dom.byId('idwReClassBtn'), 'click', IdwReClass_Click);
        on(interpolationMethod, "change", interpolationMethodChange);
        on(ordinaryKlj, "click", ordinaryKljFunctionTypeClick);
        on(generalKlj, "click", generalKljFunctionTypeClick);
        on(dom.byId('testBtn'), 'click', test_Click);
        $(window).resize(function () {
            if (isSetMask) {
                setMask();
            }
        });
    });
//显示遮罩
function setMask() {
    var mask = $('#operationMask');
    mask.css('width', $('#rightContent').width() + 25);
    mask.css('height', $(document.body).height() - 10);
    var maskloading = $('#loading-mask');
    maskloading.css('top', (mask.height() - maskloading.height()) / 2);
    maskloading.css('left', (mask.width() - maskloading.width()) / 2 - 20);
    var maskTip = $('#maskTip');
    maskTip.css('top', (mask.height() - maskTip.height()) / 2 + maskloading.height() + 10);
    maskTip.css('width', mask.width());
    mask.show();
    isSetMask = true;
}

function test_Click() {
    $('#maskTip').text('正在进行插值分析...');
    setMask();

    executeIdwTestGpServer(idwGpServerUrl, {}, 'outputRaster', 'idwLegend');
}

//获取颜色
$.ajax({
    type: 'get',
    url: 'json/color.json',
    dataType: 'json',
    error: function (error) {
        console.log(error);
    },
    success: function (data) {
        levelColors = data;
    }
});


//对多位小数进行四舍五入
//num是要处理的数字  v为要保留的小数位数
function decimal(num, v) {
    var vv = Math.pow(10, v);
    return Math.round(num * vv) / vv;
}

//插值分析测试
function executeIdwTestGpServer(gpUrl, parameters, resultParameterName, legendId) {
    var maskTip = $('#maskTip');
    var prefixTip = maskTip.text();
    require([
            "esri/tasks/query",
            "esri/tasks/QueryTask",
            "esri/geometry/Point",
            "esri/geometry/Extent",
            "esri/graphic",
            "esri/tasks/Geoprocessor",
            "esri/tasks/FeatureSet",
            "esri/layers/ImageParameters",
            "esri/tasks/GeometryService",
            "esri/layers/ArcGISDynamicMapServiceLayer",
            "dojo/on",
            "dojo/dom",
            "dojo/domReady!"
        ],
        function (Query, QueryTask, Point, Extent, Graphic, Geoprocessor, FeatureSet, ImageParameters, GeometryService, ArcGISDynamicMapServiceLayer, on, dom) {
            var UserInput="";
            weightFieldName=dom.byId("index").value;
            var DistrictNumber=$('#District option:selected').attr("value");
            var outputPixelSize=$('#outputPixelSize').val();
            var ChaZhiType=$('#interpolationMethod')[0].selectedIndex;
            var KljFunctionType;
            var functionType;
            var weight;
            var pointNumber;
            if(ChaZhiType==0)
            {
                UserInput=weightFieldName+DistrictNumber+outputPixelSize+ChaZhiType;
            }
            else if(ChaZhiType==1)
            {
                if($('#ordinaryKljFunctionType')[0].style.display=="inline")
                {
                    KljFunctionType=$("#ordinaryKljFunctionType option:selected").val();
                }
                else
                {
                    KljFunctionType=$("#generalKljFunctionType option:selected").val();
                }
                UserInput=weightFieldName+DistrictNumber+outputPixelSize+ChaZhiType+KljFunctionType;
            }
            else if(ChaZhiType==2)
            {
                functionType=$("#ytFunctionType option:selected").val();
                weight =parseFloat($('#idwYTWeight').val());
                pointNumber =parseInt($('#idwYtPointNumber').val());
                UserInput=weightFieldName+DistrictNumber+outputPixelSize+ChaZhiType+functionType+weight+pointNumber;
            }
            //判断是否同样的数据进行过分析
            if(UserInputPre==UserInput)
            {
                alert("输入数据相同");
                 $('#operationMask').hide();
                isSetMask = false;
                return;
            }
            else
            {
                UserInputPre=UserInput;
            }
            var query = new Query();
            query.returnGeometry = true;
            query.outFields = [weightFieldName];
            query.where = '1 = 1';
            var queryPointServiceUrl=gaoZhouLayerServiceUrl+"/"+$('#index option:selected').attr("ZhiBiaoType");
            var queryTask = new QueryTask(queryPointServiceUrl);
            queryTask.execute(query, function (queryResult) {
                var bchFeatures = queryResult.features;
                var max = null,
                    min = null;
                for (var index in queryResult.features) {
                    var value = queryResult.features[index].attributes[weightFieldName];
                    if (max == null || min == null) {
                        max = value;
                        min = value;
                    } else {
                        if (max < value)
                            max = value;
                        if (min > value)
                            min = value;
                    }
                }
                $('#legendTop').text('高：' + max);
                $('#legendBottom').text('低：' + min);
                //计算所有点与行政区划区域图左下角点和右上角点的距离，获取与这两点最近的attributes
                var extent;
                var queryXianDW = new Query();
                queryXianDW.returnGeometry = true;
                queryXianDW.where = "XianDm = '"+DistrictNumber+"'";
                var queryXianDWTask = new QueryTask(xzqhLayerUrl);
                queryXianDWTask.execute(queryXianDW, function (queryResult2) {
                    for(var index in queryResult2.features)
                    {
                        extent=queryResult2.features[index].geometry.getExtent();
                    }
                     var minPoint = new Point(extent.xmin, extent.ymin, queryResult.spatialReference);
                     var maxPoint = new Point(extent.xmax, extent.ymax, queryResult.spatialReference);

                var minPointGraphic = getNearbyFromFeatures(minPoint, bchFeatures);
                var maxPointGraphic = getNearbyFromFeatures(maxPoint, bchFeatures);

                bchFeatures.push(minPointGraphic);
                bchFeatures.push(maxPointGraphic);

                function getNearbyFromFeatures(point, features) {
                    var minDistance = null,
                        minDisAttributes;
                    for (var index in features) {
                        var feature = features[index];
                        var pointGeo = feature.geometry;
                        var distance = Math.pow(point.x - pointGeo.x, 2) + Math.pow(point.y - pointGeo.y, 2);
                        if (minDistance == null || minDistance > distance) {
                            minDistance = distance;
                            minDisAttributes = feature.attributes;
                        }
                    }
                    return new Graphic(point, null, minDisAttributes, null);
                }

                parameters.pointsInput = queryResult;   
                parameters.fieldname = weightFieldName;
                parameters.whereClause = "XianDm = '"+DistrictNumber+"'";
                parameters.outputPixelSize =outputPixelSize;
                if (ChaZhiType==1) 
                {
                    gpUrl=idwKLJGpServerUrl;
                    parameters.KljFunctionType=KljFunctionType;
                }
                else if(ChaZhiType==2)
                {
                    gpUrl=idwYTGpServerUrl;
                    parameters.functionType=functionType;
                    parameters.weight =weight;
                    parameters.pointNumber =pointNumber;
                }
                var gp = new Geoprocessor(gpUrl);
                gp.submitJob(parameters, function (jobInfo) {
                    if (jobInfo.jobStatus == 'esriJobSucceeded') {
                        var imageParams = new ImageParameters();
                        imageParams.imageSpatialReference = queryResult.spatialReference;
                        gp.getResultImageLayer(jobInfo.jobId, resultParameterName, imageParams, function (gpLayer) {
                            if (resultImageLayer != null) {
                                map.removeLayer(resultImageLayer);
                            }
                            gpLayer.setOpacity(0.7);
                            map.addLayer(gpLayer);
                            var pointLayer=new ArcGISDynamicMapServiceLayer(queryPointServiceUrl);
                            map.addLayer(pointLayer);
                            resultImageLayer = gpLayer;
                            $('.legend').css('display', 'none');
                            $('#' + legendId).show();
                            $('#operationMask').hide();
                            isSetMask = false;
                        });
                    }
                }, function (jobInfo) {
                    if (jobInfo.jobStatus == 'esriJobSubmitted') {
                        maskTip.html(prefixTip + '<br/>' + '已提交任务');
                    } else if (jobInfo.jobStatus == 'esriJobExecuting') {
                        maskTip.html(prefixTip + '<br/>' + '任务正在执行中');
                    } else if (jobInfo.jobStatus == 'esriJobSucceeded') {
                        maskTip.html(prefixTip + '<br/>' + '任务成功完成');
                    } else if (jobInfo.jobStatus == 'esriJobFailed') {
                        maskTip.html(prefixTip + '<br/>' + '任务执行失败');
                        alert("任务执行失败");
                        $('#operationMask').hide();
                        isSetMask = false;
                    }
                }, function (error) {
                    alert('出现错误：' + error);
                    $('#operationMask').hide();
                    isSetMask = false;
                });
                })
            }, function (error) {
                alert('点图层查询出现错误：' + error);
                $('#operationMask').hide();
                isSetMask = false;
            });
        });
}
//根据选择的插值方式显示插值条件框
function interpolationMethodChange()
{
    var interpolationMethod=$('#interpolationMethod');
    var selectedIndex=interpolationMethod[0].selectedIndex;
    for(var i=0;i<$('.IdwCondition').length;i++)
    {
        $('.IdwCondition')[i].style.display="none";
    }
    $('.IdwCondition')[selectedIndex].style.display="inline";
}
//根据选择的克里金函数类型显示函数下拉框
function ordinaryKljFunctionTypeClick()
{
    $('#ordinaryKljFunctionType')[0].style.display="inline";
    $('#generalKljFunctionType')[0].style.display="none";
}

function generalKljFunctionTypeClick()
{
    $('#ordinaryKljFunctionType')[0].style.display="none";
    $('#generalKljFunctionType')[0].style.display="inline";
}